<template>
	<view class="goods-search">
		<u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent" :enable="enable">
            <u-navbar
				title="苍蝇馆子"
				titleColor="#FFF"
                :border-bottom="false"
                :is-fixed="false"
                custom-class="nav-bg"
				:background="{background: '#116568'}"
				back-icon-color="#FFF"
            > 
            </u-navbar>
        </u-sticky>
		<view class="header-wrap">
			<!-- <u-sticky offset-top="0" h5-nav-height="0" bg-color="tranparent"> -->
				<view class="search">
					 <u-search shape="square" v-model="keyword" placeholder="输入您想查询的内容"  @search="onSearch" wrap-bg-color="#F5F5F5" bg-color="#FFF" placeholderColor="#739495" searchIconColor="#366667" color="#116568" height="84"></u-search>
				</view>
			<!-- </u-sticky> -->
		</view>
		<view  class="content">
			<view class="search-box row">
				<scroll-view id="_scroll" :scroll-x="true" class="scroll-view-h" scroll-with-animation :scroll-left="slider.scrollLeft">
					<view class="area-list">
						<text class="area-item" :class="(activeIndex === areaIndex) ? 'active' : ''" v-for="(area, areaIndex) in areaData" :key="area.id" @tap="handleArea(areaIndex)">
							{{area.name}}
						</text>
					</view>
				</scroll-view>
				<view class="filter-box row" @tap="handleFilter">
					<view class="divide-line"></view>
					筛选
					<image src="../../static/images/arrow_down.png" class="filter-img" />
				</view>
			</view>
			<view class="goods-list">
				<view  class="double">
					<fly-goods-list :list="goodsList"></fly-goods-list>
				</view>
			</view>
			<loading-footer :status="status" slotEmpty>
				<u-empty text="暂无数据~" slot="empty"></u-empty>
			</loading-footer>
		</view>
<!-- 		<u-picker v-model="pickerShow" :columns="pickerColumns" :immediateChange="true"   keyName="name" @confirm="confirmHandler" @change="changeHandler"></u-picker> -->
		<u-picker
		    mode="selector"
		    v-model="pickerShow"
		    :range="pickerColumns"
			range-key="name"
		    @confirm="confirmHandler"
		></u-picker>
	</view>
</template>

<script>
	import {
		getGoodsSearch,
		getSearchpage,
		clearSearch,
		getFlyRestaurant,
		getCityByLocation,
		getCityArea
	} from '@/api/store';
	import {
		trottle,
		loadingFun,
		getRect
	} from '@/utils/tools';
	import {
		loadingType
	} from '@/utils/type';
	import Cache from '@/utils/cache'
	import { CITY_CODE,  CURRENT_LOCATION, DEFAULT_CITY } from "@/config/cachekey"

	export default {
		data() {
			return {
				keyword: '',
				status: loadingType.LOADING,
				page: 1,
				goodsType: 'double',
				goodsList: [],
				priceSort: '',
				saleSort: '',
				showHistory: false,
				hotList: [],
				historyList: [],
				// 当前位置信息
				currentLocation: {},
				// 城市信息
				cityData: {},
				// 区域信息
				areaData: [],
				activeIndex: 0,
				slider: {
					left: 0,
					width: 0,
					scrollLeft: 0
				},
				pickerShow: false,
				pickerColumns: [],
				user_lat: '', // 维度
				user_lng: '', // 经度
				city_coding: '', // 城市code
				area_code: '', // 区域code
			};
		},
		computed: {
			district(){
				return this.areaData && this.areaData[this.activeIndex] && this.areaData[this.activeIndex].id;
			}
		},
		components: {},
		props: {},
		onLoad(options) {
			this.onNormal = trottle(this.onNormal, 500, this);
			this.onPriceSort = trottle(this.onPriceSort, 500, this);
			this.onSaleSort = trottle(this.onSaleSort, 500, this);
			this.onSearch = trottle(this.onSearch, 500, this);
			
			// this.getGoodsSearchFun();
		},
		onShow(){
			// console.log('this.currentLocation', this.currentLocation)
			// let { longitude, latitude } = this.currentLocation
			// if(longitude && latitude){ // 当前位置存在直接初始化活动列表
			//     this.getCityAreaFn()
			// 	this.getGoodsSearchFun()
			// }else{ // 当前位置不存在重新获取位置后再请求活动列表
			// 	this.getCurrentCity()
			// }
			this.getCityAreaFn();
		},
		onReachBottom: function() {
			this.getGoodsSearchFun();
		},
		onPullDownRefresh() {
		    this.activeIndex = ''
			this.page = 1
		    this.getGoodsSearchFun()
		},
		methods: {
			confirmHandler(val){
				   console.log('confirm', val)
				   this.activeIndex = val[0];
				   this.pickerShow = false
				   this.page = 1
				   this.getGoodsSearchFun();
			},
			changeHandler(e){
				  console.log('confirm', e)
			},
			handleArea(index){
				this.activeIndex = index
				console.log('this.activeIndex', this.activeIndex)
				this.page = 1
				this.status = loadingType.LOADING
				this.goodsList = []
				this.getGoodsSearchFun();
			},
			// 授权位置信息
			getCurrentCity(fn) {
				uni.getSetting({
					success: res => {
						if (res.authSetting && res.authSetting.hasOwnProperty("scope.userLocation")) {
							if (res.authSetting["scope.userLocation"]) {
								this.getLocation(fn)
							} else {
								uni.hideLoading()
								uni.showModal({
									title: '提示',
									content: '请重新授权获取您的地理位置，否则部分功能将无法使用',
									success: (res) => {
										if (res.confirm) {
											uni.openSetting({
												success: () => this.getLocation(fn)
											})
										} else {
											uni.showToast({
												title: '请授权获取您的地理位置，否则部分功能将无法使用',
												icon: 'none',
												duration: 2000
											})
										}
									},
									fail: (res) => {
										uni.showToast({
											title: '位置获取失败',
											icon: "none",
											duration: 2000
										})
									}
								})
							}
						} else {
							this.getLocation(fn)
						}
					}
				})
			},
			// 获取当前位置坐标
			getLocation (fn) {
			      let that = this
			      // 获取用户是否开启 授权获取当前的地理位置、速度的权限。
			      uni.getSetting({
			        success (res) {
			          console.log(res)
			
			          // 如果没有授权
			          if (!res.authSetting['scope.userLocation']) {
			            // 则拉起授权窗口
			            uni.authorize({
			              scope: 'scope.userLocation',
			              success () {
			                //点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
			                uni.getLocation({
			                  type: 'wgs84',
							  geocode: true,//设置该参数为true可直接获取经纬度及城市信息
			                  success: function (res) {
								console.log('允许授权res', res)
			                    that.x = res.longitude
			                    that.y = res.latitude
			                    console.log(res)
			                    console.log('当前位置的经度：' + res.longitude)
			                    console.log('当前位置的纬度：' + res.latitude)
								that.currentLocation = res
								that.getCurCity()
								
			                    // uni.showToast({
			                    //   title: '当前位置的经纬度：' + res.longitude + ',' + res.latitude,
			                    //   icon: 'success',
			                    //   mask: true
			                    // })
			                  }, fail (error) {
			                    console.log('失败', error)
								uni.showToast({
									title: error.errMsg,
									icon: 'error',
									mask: true
								})
			                  }
			                })
			              },
			              fail (error) {
			                //点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
			                console.log('拒绝授权', error)
			
			                uni.showModal({
			                  title: '提示',
			                  content: '若点击不授权，将无法使用位置功能',
			                  cancelText: '不授权',
			                  cancelColor: '#999',
			                  confirmText: '授权',
			                  confirmColor: '#f94218',
			                  success (res) {
			                    console.log(res)
			                    if (res.confirm) {
			                      // 选择弹框内授权
			                      uni.openSetting({
			                        success (res) {
			                          console.log(res.authSetting)
			                        }
			                      })
			                    } else if (res.cancel) {
			                      // 选择弹框内 不授权
			                      console.log('用户点击不授权')
			                    }
			                  }
			                })
			              }
			            })
			          } else {
			            // 有权限则直接获取
			            uni.getLocation({
			              type: 'wgs84',
						  geocode: true,//设置该参数为true可直接获取经纬度及城市信息
			              success: function (res) {
			                that.x = res.longitude
			                that.y = res.latitude
			                console.log(res)
			                console.log('当前位置的经度：' + res.longitude)
			                console.log('当前位置的纬度：' + res.latitude)
							console.log('允许授权res', res)
							that.currentLocation = res
							that.getCurCity()
			                // uni.showToast({
			                //   title: '当前位置的经纬度：' + res.longitude + ',' + res.latitude,
			                //   icon: 'success',
			                //   mask: true
			                // })
			              }, fail (error) {
			                uni.showToast({
			                  title: '请勿频繁调用！',
			                  icon: 'none',
			                })
			                console.log('失败', error)
			              }
			            })
			          }
			        }
			      })
			},
			async getCurCity(){
				console.log('this.currentLocation', this.currentLocation)
				let { longitude, latitude } = this.currentLocation
				let params = {
					lng: longitude,
					lat: latitude
				}
				let res = await getCityByLocation(params)
				console.log('getCurCity--res', res)
				this.district = res.city_area_code
				this.cityData = res.data;
				console.log('this.cityData', this.cityData)
				this.getCityAreaFn()
			},
			async getCityAreaFn(){
				console.log('this.cityData', this.cityData)
				// let { city_code } = this.cityData
				// if(uni.getStorageSync(CITY_CODE)){
				// 	city_code = uni.getStorageSync(CITY_CODE)
				// }
				// let params = {
				// 	city_code: city_code
				// }
				let params = {
					city_code:  Cache.get(CITY_CODE) || ''
				}
				console.log('苍蝇馆子根据城市code获取区域参数：', params)
				let res = await getCityArea(params)
				console.log('getCurCity--res', res)
				this.areaData = res.data;
				console.log('this.areaData', this.areaData)
				this.pickerColumns = res.data;
				console.log('list-this.pickerColumns ', this.pickerColumns )
				this.getGoodsSearchFun()
			},
			handleFilter(){
				console.log('filter')
				this.pickerShow = true;
				console.log('this.pickerShow', this.pickerShow)
			},
			onChange(e) {
				this.keyword = e.value
			},

			onNormal() {
				this.priceSort = ''
				this.saleSort = ''
				this.onRefresh();
			},

			onPriceSort() {
				let {
					priceSort
				} = this;
				this.saleSort = ''
				this.priceSort = priceSort == 'asc' ? 'desc' : 'asc'
				this.onRefresh();
			},

			onSaleSort() {
				let {
					saleSort
				} = this;
				this.priceSort = ''
				this.saleSort = saleSort == 'desc' ? 'asc' : 'desc'
				this.onSearch();
			},
			onClear() {
				if (this.id) {
					this.onSearch();
				}
			},
			onSearch() {
				this.onRefresh()
			},
			onRefresh() {
				this.showHistory = false
				this.page = 1
				this.goodsList = []
				this.status = loadingType.LOADING
				this.$nextTick(() => {
					this.getGoodsSearchFun();
				});
			},

			onChangeKeyword(item) {
				this.keyword = item
				this.showHistory = false
				this.onRefresh();
			},

			async getGoodsSearchFun() {
				let {
					page,
					goodsList,
					keyword,
					// priceSort,
					// saleSort,
					status,
					user_lat,
					user_lng,
					city_coding,
					area_code,
					district
				} = this;
				if (status == loadingType.FINISHED) return;
				
				// let { longitude:lng, latitude:lat } = this.currentLocation
				// console.log('this.cityData', this.cityData)
				// let {city_code: province} = this.cityData
				// let {district} = this
				// console.log('district', district)
				let { longitude, latitude } = Cache.get(CURRENT_LOCATION) // 当前位置
				let defaultCity = Cache.get(DEFAULT_CITY); // 默认城市，成都
				console.log('defaultCity', defaultCity)
				
				const params = {
					page_no: page,
					title: keyword,
					lat: latitude || defaultCity.lat, // 维度，没有获取到经纬度就取默认的经纬度
					lng: longitude || defaultCity.lon, // 经度，没有获取到经纬度就取默认的经纬度
					province: Cache.get(CITY_CODE) || '', // 城市代码
					district: district || '',  // 区域代码
					
					// lat: lat, // 维度
					// lng: lng, // 经度
					// province: province, // 城市代码
					// district: district, // 区域代码
				}
				console.log('苍蝇馆子列表参数：', params)
				const data = await loadingFun(getFlyRestaurant, page, goodsList, status, params)
				if (!data) return
				this.page = data.page
				this.goodsList = data.dataList
				this.status = data.status
			},
		}
	};
</script>
<style lang="scss">
	.goods-search {
		.header-wrap {
			.search {
				// box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.03);
				position: relative;
				z-index: 1;
			}

			.header {
				height: 80rpx;

				.tag {
					height: 100%;
					flex: 1;
				}
			}
		}


		.content {
			.search-words {
				padding-left: 24rpx;
				padding-bottom: 20rpx;

				.title {
					padding: 26rpx 0;
				}

				.words {
					.item {
						line-height: 52rpx;
						height: 52rpx;
						padding: 0 24rpx;
						background-color: #F5F5F5;
					}
				}
			}
			
			.search-box{
				margin: 20rpx 0;
				padding: 0 20rpx;
				.scroll-view-h {
					height: 80rpx;
					line-height: 80rpx;
					white-space: nowrap;
					width: 570rpx;
					box-sizing: border-box;
				}
				.area-list{
					flex: 1;
					.area-item{
						margin-right: 32rpx;
						font-size: 28rpx;
						color: #999999;
						line-height: 40rpx;
						&.active{
							font-weight: 500;
							color: #265E5F;
						}
					}
				}
				.filter-box{
					font-size: 28rpx;
					color: #333333;
					line-height: 40rpx;
					.divide-line{
						width: 2rpx;
						height: 28rpx;
						background: #B7BABA;
						margin-right: 28rpx;
					}
					.filter-img{
						margin-left: 20rpx;
						width: 26rpx;
						height: 14rpx;
					}
				}
			}

			.goods-list {
				overflow: hidden;
			}
		}
	}
</style>
